import { Context, Next } from "koa";
import { verify } from "../utils/auth";
import response from "../utils/response";

const testRegularList: RegExp[] = [
  // /\/article\/getArticleList/,
  // /\/deleteArticle/
] //  开发时去除token要求
const regularList: RegExp[] = [/\/user\/queryUserName/, /\/user\/register/, /\/user\/login/, /\/article\/getArticleList/, /\/article\/getArticle/, ...testRegularList];
// token
export default function AuthMiddlewart(ctx: Context, next: Next) {
  // 过滤部分无需登录状态的路由

  const regular = regularList.find((regular) => regular.test(ctx.path));
  if (regular) {
    // 不需要验证token
    return next();
  } else {
    // 需要验证
    const token =
      ctx.request.header.authorization || (ctx.request.query.token as string);
    if (!token) {
      response.error(ctx, "请携带token");
    } else {
      // 取到token才有校验的必要
      const tokenData = token.split(" ");
      const res = verify(tokenData[tokenData.length - 1]);
      //  todo: 暂时没有，比对过期时间， 登录ip,设备等。。 todo
      if (res.error) {
        response.error(ctx, res.error as string);
      } else {
        const data = res.data as { userId: string };
        ctx.user = {
          userId: data.userId,
        };
        return next();
      }
    }
  }
}
